package com.peter.proxy.hkgolden.web;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.peter.proxy.hkgolden.api.ContentService;
import com.peter.proxy.hkgolden.api.Topic;

@Singleton
@SuppressWarnings("serial")
public class TopicsServlet extends HttpServlet {

	private Injector injector;

	@Inject
	public void setInjector(Injector injector) {
		this.injector = injector;
	}

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.debug("doGet()");

		long start = System.currentTimeMillis();

		String channel = null;
		int page = 1;
		try {
			channel = req.getParameter("ch");
			try {
				page = Integer.parseInt(req.getParameter("p"));
			} catch (Exception e) {
			}

			final ContentService contentService = injector
					.getInstance(ContentService.class);
			logger.trace("contentService = {}", contentService);

			final Map<String, String> channels = contentService.channels();
			logger.debug("channels.size() = {}", channels.size());
			req.setAttribute("channels", channels);
			final Collection<Topic> topics = contentService.topics(channel,
					page);
			logger.trace("topics.size() = {}", topics.size());
			final TreeSet<Topic> topics1 = new TreeSet<Topic>();
			topics1.addAll(topics);
			
			req.setAttribute("topics", topics1);
			req.setAttribute("usedTime", System.currentTimeMillis() - start);
			req.getRequestDispatcher("/topics.jsp").forward(req, resp);
		} catch (IOException e) {
			logger.error("", e);
		}
	}
}
